package com.xuxu.blog.service.loginAndregister;

import com.xuxu.blog.utils.EmailUtils;
import com.xuxu.blog.utils.RandomUtil;
import com.xuxu.blog.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @className: EmailService
 * @author: Maxuxu
 * @date: 2022/8/23 17:34
 * @description: 邮件发送的服务层
 */
@Service
@Slf4j
public class EmailService {
    @Resource
    private EmailUtils emailUtils;

    @Autowired
    private RedisUtils redisUtil;

    /**
     * 发送邮箱验证码验证发送短信的次数
     * @param email
     */
    public boolean verifyCount(String email) throws Exception {
        String countKey = "VerifyCode" + email +":count";
        String codeKey = "VerifyCode" + email + ":code";
        Integer count = (Integer) redisUtil.get(countKey);
        // Integer count = redisUtil.getStringtoInteage(countKey);
        // log.error("向手机号：{} 已经发送的次数是：{}",countKey,count);
        if (count == null){
            //    第一次发送,设置发送次数是1
            //    限制60分种内只能发送3次
            // log.error("发送次数：{}",1);
            redisUtil.set(countKey,1,60*60);
        }
        else if (count<=2){
            // log.error("发送次数：{}",count);
            redisUtil.incr(countKey,1);
        }else if(count>2){
            // System.out.println("发送次数超过三次了");
            return false;
        }
        //    发送验证码到redis
        String vscode = String.valueOf(RandomUtil.random6Num());
        log.debug("存入的验证码是：{}",vscode);
        // 验证码20分钟内有效
        redisUtil.set(codeKey,vscode ,20*60);
        String msg = "本次的验证码是：【" + vscode + "】，请在30分钟内注册，过期失效！";
        emailUtils.sendSimpleEmail(email,"验证码邮件",msg);
        return true;
    }

    /**
     * 验证邮件验证码
     * @param email
     * @param code
     */
    public int verifyCode(String email,String code) {
        // 从redis中获取验证码
        String codeKey = "VerifyCode" + email + ":code";
        String redisCode = (String) redisUtil.get(codeKey);
        //    判断
        if (redisCode!=null) {
            if (redisCode.equals(code)) {
//                System.out.println("成功");
                redisUtil.del(codeKey);
                return 1;
            } else {
//                System.out.println("失败");
                return 0;
            }
        } else {
//            System.out.println("验证码失效");
            return 2;
        }

    }
}
